/*action create by pionner code builder*/
package com.pioneer.app.proview;

import java.io.*;

import org.hibernate.Transaction;

import java.util.List;


import java.util.Iterator;


import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.ActionContext;

import java.io.Serializable;
import java.nio.charset.Charset;

public class ProcessAction implements Action,Serializable {

	// key
	private java.lang.String id;
	private String title;
	private File img;
	private String seed;
	private String imgFileName;
	private String btn;
	private java.lang.String[] ids;
	private Process process;
	private java.lang.String name;
	private java.lang.String remark;
	private List objects=null;
	private String condition=null;
	private String fromTree=null;
	private String act=null;
	//同此种记录关联记录的编号
	private String rlid=null;
	//访问后返回页面地址名称
	private String returnpage=null;	//系统运行错误信息
	private String errorInfo=null;	/** 默认构造方法 */
	public ProcessAction(){
	}
	/** full constructor */
	public ProcessAction(java.lang.String name,java.lang.String remar){
		this.name=name;
		this.remark=remark;

	}
	public void setId(java.lang.String id){
		this.id=id;
	}
	public java.lang.String getId(){
		return id;
	}

	public void setIds(java.lang.String[] ids){
		this.ids=ids;
	}
	public java.lang.String[] getIds(){
		return ids;
	}

	public void setProcess(Process process){
		this.process=process;
	}
	public Process getProcess(){
		return process;
	}

	public void setName(java.lang.String name){
		this.name=name;
	}
	public java.lang.String getName(){
		return name;
	}

	public void setRemark(java.lang.String remark){
		this.remark=remark;
	}
	public java.lang.String getRemark(){
		return remark;
	}

	public List getObjects() {
		return objects;
	}

	public void setObjects(List objects) {
		this.objects = objects;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public String getRlid() {
		return rlid;
	}

	public void setRlid(String rlid) {
		this.rlid = rlid;
	}

	public String getReturnpage() {
		return returnpage;
	}

	public void setReturnpage(String returnpage) {
		this.returnpage = returnpage;
	}

	public String getErrorInfo() {
		return errorInfo;
	}

	public void setErrorInfo(String errorInfo) {
		this.errorInfo = errorInfo;
	}

	public String execute() throws Exception {
		return "SUCESS";
	}

	public String doList(){
		try{
		ProcessDAO dao=new ProcessDAO();
		this.objects=dao.findByCondition(condition);
		}catch(Exception e){
			this.errorInfo="取列表数据出错";
		}
		return "list";
	}

	public String doAdd(){
		return "add";
	}

	public String doEdit(){
		try{
		ProcessDAO dao=new ProcessDAO();
		this.process=dao.findById(id);
		this.sedObj();;
		}catch(Exception e){
			this.errorInfo="取列表数据出错";
		}
		return "edit";
	}

	public String doSave(){
		Transaction tx=null;
		try {
			this.buildObj();
			ProcessDAO dao=new ProcessDAO();
			tx=dao.getSession().beginTransaction();
			if(null!=this.act){
			try{
					dao.add(process);
			}catch(Exception e){
				tx.rollback();
				this.errorInfo="添加数据出错";
			}
			}else{
//			update the object
			try{
					dao.getSession().clear();
					dao.update(process);
			}catch(Exception e){
				tx.rollback();
					this.errorInfo="保存数据出错";
			}
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			this.errorInfo="系统出错";
		}
		if(null==this.returnpage){
			this.returnpage="list";
		}
		return returnpage;
	}

	public String doDetail(){
			ProcessDAO dao=new ProcessDAO();
		this.process=dao.findById(id);
		this.sedObj();
		if(null==this.returnpage){
			this.returnpage="list";
		}
		return returnpage;
	}

	public String doDelete(){
		
		try{
			ProcessDAO dao=new ProcessDAO();			
			dao.deleteObjs(ids);
		}catch(Exception e){
			this.errorInfo="删除记录,系统出错";
		}
		if(null==this.returnpage){
			this.returnpage="list";
		}
			return returnpage;
	}
	
	//更改全站标题和logo的方法
	public String doTitle(){
		try{
			
			//修改标题
			
			String path=this.getClass().getClassLoader().getResource("").getPath();
			path=path.substring(0, path.indexOf("WEB-INF"));
			
			FileInputStream in=new FileInputStream(path+"main.jsp");
			StringBuffer   buf=new StringBuffer();
			BufferedReader   breader = new BufferedReader(new InputStreamReader(in,"UTF-8"));   
			while(breader.ready())        
                buf.append((char)breader.read());      
          breader.close(); 
          in.close();         
          int start=buf.indexOf("<title>")+7;
          int end=buf.indexOf("</title>");
          if(title.length()>0){
        	  buf.replace(start, end, title);
          }
          if(btn.equals("preview")){
        	  path=path+"main"+seed+".jsp";
        	  start=buf.indexOf("header.jsp");
              end=buf.indexOf("header.jsp")+10;
              buf.replace(start, end, "header1.jsp");
          }else{
        	  path=path+"main.jsp";
          }
          FileOutputStream fos = new FileOutputStream(path);
          Writer out = new OutputStreamWriter(fos, "UTF-8");
          out.write(buf.toString());
          out.close();
          fos.close();
			
			//上传图片
		if(!imgFileName.equals("")){
			path=this.getClass().getClassLoader().getResource("").getPath();
			path=path.substring(0, path.indexOf("WEB-INF"));
			
			 InputStream imgIn = null ;
	            OutputStream imgOut = null ;
	                        
	                imgIn = new BufferedInputStream( new FileInputStream(img), 1024);
	                imgOut = new BufferedOutputStream( new FileOutputStream(path+"images/"+imgFileName), 1024);
	                byte [] buffer = new byte [1024];
	                while (imgIn.read(buffer) > 0 )  {
	                    imgOut.write(buffer);
	                }
	                 imgOut.close();
	                 imgIn.close();
		}         
	                 
	       //修改css
		path=this.getClass().getClassLoader().getResource("").getPath();
		path=path.substring(0, path.indexOf("WEB-INF"));
	                path=path+"themes\\default\\";
	                
	     			FileInputStream cssin=new FileInputStream(path+"style.css");
	     			StringBuffer   cssbuf=new StringBuffer();
	     			BufferedReader   cssbreader = new BufferedReader(new InputStreamReader(cssin,"UTF-8"));   
	     			while(cssbreader.ready())        
	                     cssbuf.append((char)cssbreader.read());      
	               cssbreader.close(); 
	               cssin.close();         
	               start=cssbuf.indexOf("#header{background:url(../../images/")+36;
	               end=cssbuf.indexOf(") no-repeat; height:97px;width:100%");
	               if(!imgFileName.equals("")){
	            	   cssbuf.replace(start, end, imgFileName);
	               }
	               if(btn.equals("preview")){
		              	  path=path+"style1.css";
		                }else{
		              	  path=path+"style.css";
		                }
	               FileOutputStream cssfos = new FileOutputStream(path);
	               Writer cssout = new OutputStreamWriter(cssfos, "UTF-8");
	               cssout.write(cssbuf.toString());
	               cssout.close();
	               cssfos.close();
	               
	        //修改header
	if(btn.equals("preview")){
		path=this.getClass().getClassLoader().getResource("").getPath();
		path=path.substring(0, path.indexOf("WEB-INF"));
		path=path+"modules\\layout\\";
		
		FileInputStream hin=new FileInputStream(path+"header.jsp");
		StringBuffer   hbuf=new StringBuffer();
		BufferedReader   hbreader = new BufferedReader(new InputStreamReader(hin,"UTF-8"));   
		while(hbreader.ready())        
            hbuf.append((char)hbreader.read());      
      hbreader.close(); 
      hin.close();         
      int hstart=hbuf.indexOf("style.css");
      int hend=hbuf.indexOf("style.css")+9;
      hbuf.replace(hstart, hend, "style1.css");
     
      FileOutputStream hfos = new FileOutputStream(path+"header1.jsp");
      Writer hout = new OutputStreamWriter(hfos, "UTF-8");
      hout.write(hbuf.toString());
      hout.close();
      hfos.close();
	
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return "detail";
	}
	/*******************取到选择列表*************************/
	public String doCheckList(){
		try{
			ProcessDAO dao=new ProcessDAO();
			
			this.objects=dao.findByCondition(condition);
			//	确定那些被选中了
			if(null==rlid){
				rlid =(String)ActionContext.getContext().getSession().get("rlid");
				//ActionContext.getContext().getSession().remove("rlid");
			}
			if(null!=this.objects){
				Process process=null;
//		开发人员在此填入关联这种记录的id号名称
				List checkList=getrelationList("roleId",new Integer(rlid));
//				System.out.println("checkList.size()="+checkList.size());
				Iterator it=this.objects.iterator();
				while(it.hasNext()){
					process =(Process)it.next();
					if(isCheck(process.getId(), checkList))
						process.setChecked("checked");
				}
			}
			dao.getSession().close();
		}catch(Exception e){
			this.errorInfo="系统出错";

		}
	return "list";
	}

	/*****************判断是否被选中 ,开发人员要修改此处******************/
	private boolean isCheck(java.lang.String processId,List checkList){
		Iterator it=checkList.iterator();
		RoleProcess rlObj=null;
		while(it.hasNext()){
			rlObj=(RoleProcess)it.next();
			//开发人员根据数据类型修改判断方法
			if(processId.equalsIgnoreCase(rlObj.getProcessId())){
				return true;
			}
		}
		return false;
	}

	/************************根据相管理对象的id取到同本类型对象关联的关系list***************************/
	private List getrelationList(String key,Object value){
		RoleProcessDAO dao=new RoleProcessDAO();
		List objs=dao.findByProperty(key,value);
		return objs;
	}

	/*************************保存关联操作结果********************************/
	public String doRoleCheckSave(){
		if(null!=this.ids){
			java.lang.String id=null;
			//				清空所有关联对象所关联到本对象的记录。
			RoleProcessDAO rlDao=new RoleProcessDAO();
			rlDao.deleteByCondition("roleId="+rlid);
			RoleProcess rlObj=null;
			Transaction tx=rlDao.getSession().beginTransaction();
			for(int i=0;i<this.ids.length;i++){
				rlObj=new RoleProcess();
				rlObj.setProcessId(ids[i]);
				rlObj.setRoleId(new Integer(rlid));
				rlDao.add(rlObj);
			}
		tx.commit();
		rlDao.getSession().clear();
		}
		if(null==this.returnpage){
		ActionContext.getContext().getSession().put("rlid", this.rlid);
			returnpage="list";
		}
		return returnpage;
	}
	private void buildObj(){
		this.process=new Process();
		this.process.setId(this.id);
		this.process.setName(this.name);
		this.process.setRemark(this.remark);
	}
	private void sedObj(){

		if(null!=this.process){
			this.id=this.process.getId();
			this.name=this.process.getName();
			this.remark=this.process.getRemark();

		}
	}
	public String getAct() {
		return act;
	}
	public void setAct(String act) {
		this.act = act;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public File getImg() {
		return img;
	}
	public void setImg(File img) {
		this.img = img;
	}
	public String getImgFileName() {
		return imgFileName;
	}
	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}
	public String getBtn() {
		return btn;
	}
	public void setBtn(String btn) {
		this.btn = btn;
	}
	public String getSeed() {
		return seed;
	}
	public void setSeed(String seed) {
		this.seed = seed;
	}
}